﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using Microsoft.SharePoint.Utilities;

namespace LanguageConfigurationSolution
{
    public static class ConfigurationReader
    {
        private static string KeyColumnName = "Title";
        /// <summary>
        /// Retrieves the configuration value for a specific key
        /// </summary>
        /// <param name="configurationKey">The key for the configuration list,  with which a value can be retrieved</param>
        /// <param name="configurationListName"> The name of the configuration list</param>
        /// <returns>The value matching a given key, or empty string otherwise</returns>
        public static String GetConfigurationValue(String configurationKey, string configurationListName, string ColName)
        {

            String returnValue = String.Empty;
            SPList configurationList = null;

            try
            {
                if (string.IsNullOrEmpty(configurationListName) && SPContext.Current != null)
                {
                    string configurationListUrl = SPUrlUtility.CombineUrl(SPContext.Current.Site.ServerRelativeUrl , SPContext.Current.Site.RootWeb.Properties["LanguageConfigurationList"] );
                    configurationList = SPContext.Current.Site.RootWeb.GetList(configurationListUrl);
                }
                else
                {
                    configurationList = SPContext.Current.Site.RootWeb.Lists[configurationListName];
                }
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(
                        typeof(ConfigurationReader).FullName,
                        string.Format("Error occured accessing list '{0}'.{1}{2}", new string[] { configurationListName, Environment.NewLine, ex.ToString() }),
                        EventLogEntryType.Error);
                });
                throw;
            }

            String caml = String.Format("<Where><Eq><FieldRef Name='{1}'></FieldRef><Value Type='Text'>{0}</Value></Eq></Where>", configurationKey, KeyColumnName);
            SPQuery query = new SPQuery();
            query.Query = caml;

            SPListItemCollection queryResults = configurationList.GetItems(query);
            if (queryResults.Count == 0)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(
                        typeof(ConfigurationReader).FullName,
                        string.Format("No value for key '{0}' in list '{1}'.", new string[] { configurationKey, configurationListName }),
                        EventLogEntryType.Warning);
                });
            }
            else
            {
                try
                {
                    returnValue = null;
                    //object obj = queryResults[0]["ConfigValue"];

                    if (Microsoft.SharePoint.SPContext.Current != null)
                    {
                        object obj = null; ;
                        if (string.IsNullOrEmpty(ColName))
                        {
                            // TwoLetterIsoLanguageName is NON capitols ad nl, en, du
                            obj = queryResults[0][Microsoft.SharePoint.SPContext.Current.Web.Locale.TwoLetterISOLanguageName];
                        }
                        else
                        {
                            obj = queryResults[0][ColName];
                        }
                        if (obj != null) returnValue = obj.ToString();
                    }
                }
                catch
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate
                    {
                        EventLog.WriteEntry(
                            typeof(ConfigurationReader).FullName,
                            string.Format("Unable to retrieve value for key '{0}' in list '{1}' for culture '{2}'.", new string[] { configurationKey, configurationListName, Microsoft.SharePoint.SPContext.Current.Web.Locale.TwoLetterISOLanguageName }),
                            EventLogEntryType.Information);
                    });
                }
            }

            return returnValue;
        }
    }
}
